import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class JsonEditorPage extends StatefulWidget {
  final String jsonString;

  JsonEditorPage({@required this.jsonString});

  @override
  State<StatefulWidget> createState() {
    return _JsonEditorPageState();
  }
}

class _JsonEditorPageState extends State<JsonEditorPage> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  String _assetsPath = "";

  @override
  void initState() {
    super.initState();
    //TextField赋初始值
    _controller.text = widget.jsonString;
    _initApplicationDocumentsDirectory();
  }

  //获取应用build后的主目录
  Future<void> _initApplicationDocumentsDirectory() async {
    final Directory applicationDocumentsDirectory =
        await getApplicationDocumentsDirectory();

    final Directory directory =
        Directory(applicationDocumentsDirectory.parent.absolute.path);
    _iterateAllFiles(directory);
    print('assetsPath---$_assetsPath');
  }

  //遍历所有文件目录，查找assets文件夹路径
  void _iterateAllFiles(Directory directory) {
    for (final FileSystemEntity fileSystemEntity in directory.listSync()) {
      if (FileSystemEntity.isDirectorySync(fileSystemEntity.absolute.path)) {
        //是目录,递归查找
//        print('directory---' + fileSystemEntity.absolute.path);

        if (fileSystemEntity.absolute.path
            .endsWith("build/flutter_assets/assets")) {
          _assetsPath = fileSystemEntity.absolute.path;
          break;
        }

        _iterateAllFiles(Directory(fileSystemEntity.absolute.path));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_controller.text == widget.jsonString) {
          return true;
        } else {
          //json有改动过
          _showConfirmSaveDialog(
              "Json has been changed, do you want to save it to mock the server response data?");

          return false;
        }
      },
      child: Scaffold(
          appBar: AppBar(
            title: const Text("Json Editor"),
          ),
          body: Column(
            children: <Widget>[
              Container(
                  margin: const EdgeInsets.only(left: 10, top: 10),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "Edit the following json to mock the data :",
                    style: TextStyle(
                        color: Colors.blueAccent,
                        fontSize: 16,
                        fontWeight: FontWeight.bold),
                  )),
              Container(
                height: 1.5,
                color: Colors.blue,
                margin: EdgeInsets.fromLTRB(10, 10, 10, 0),
              ),
              Expanded(
                child: Container(
                    margin: EdgeInsets.all(10),
                    child: TextField(
                        decoration: InputDecoration(
//                          border: InputBorder.none,
                            ),
                        controller: _controller,
                        focusNode: _focusNode,
                        maxLines: 1000000)),
              ),
              SizedBox(
                height: 13,
              ),
              RaisedButton(
                color: Colors.blue[300],
                onPressed: () {
                  _showConfirmSaveDialog(
                      "Save the json to mock the server response data");
                },
                child: Text("Save"),
              ),
              SizedBox(
                height: 20,
              ),
            ],
          )),
    );
  }

  void _showConfirmSaveDialog(String content) {
    //让TextField失去焦点
    _focusNode.unfocus();

    showDialog(
        context: context,
        builder: (BuildContext buildContext) {
          return CustomConfirmDialog(
            content: content,
            leftButtonTitle: "Cancel",
            rightButtonTitle: "Confirm",
            rightButtonColor: Colors.blueAccent,
            confirmCallback: () {
              Navigator.of(buildContext).pop();
              _saveMockJson();
            },
            cancelCallback: () {
              Navigator.of(buildContext).pop();
              Navigator.of(context).pop();
            },
          );
        });
  }

  //保存mockJson
  void _saveMockJson() {
    print('onPressed---${_controller.text}');

    try {
      jsonDecode(_controller.text);
      _createFile("$_assetsPath/mock", "mockJson.json");

      Navigator.of(context).pop();

//      Toast.show(_controller.text.toString());
    } catch (error) {
      print('error---$error');
    }
  }

  //创建mockJson文件
  void _createFile(String path, String fileName) {
    final File file = File("$path/$fileName");

    if (!file.existsSync()) {
      file.createSync();
    }

    //mock数据写入文件
    file.writeAsStringSync(_controller.text);

    //以字符串形式读取
//    String readAsStringSync = file.readAsStringSync();
//    print('readAsStringSync---' + readAsStringSync);
  }
}
